package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sangeng.config.RedisCache;
import com.sangeng.contants.SystemConstants;
import com.sangeng.dto.ArticleDto;
import com.sangeng.entity.SgArticleTag;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.mapper.Exception.SystemException;
import com.sangeng.service.CategoryService;
import com.sangeng.service.SgArticleTagService;
import com.sangeng.vo.*;
import com.sangeng.entity.Article;
import com.sangeng.entity.ResponseResult;
import com.sangeng.mapper.ArticleMapper;
import com.sangeng.service.ArticleService;
import com.sangeng.util.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    CategoryService categoryService;
    @Autowired
    ArticleService articleService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    SgArticleTagService sgArticleTagService;
    @Override
    public ResponseResult getHotarticleList() {

        //查询热门用户，封装成ResponseResult对象返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus,0);
        queryWrapper.orderByDesc(Article::getViewCount);
        Page<Article> articlePage = new Page<>(1, 10);
        //this.getBaseMapper().selectPage(page, queryWrapper),他里面会调用BaseMapper里面的方法查询
        page(articlePage,queryWrapper);

        List<Article> articles = articlePage.getRecords();
        List<HotArticleVo>  hotArticleVo =    BeanCopyUtils.copyBean(articles, HotArticleVo.class);
       return ResponseResult.okResult(hotArticleVo);
    }

    @Override
    public ResponseResult getArticleList(Integer pageNum,Integer pageSize,Long categoryId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        //当categoryId不为空时根据categoryId去查询,如果为空，那么
        queryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,Article::getCategoryId,categoryId)
                //状态为以发布状态
                .eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL)
                //置顶文章，根据is_top字段
                .orderByDesc(Article::getIsTop);

        //分页，根据传入的pageNum，pageSize
        Page<Article> page = page(new Page<Article>(pageNum, pageSize), queryWrapper);
        List<Article> articles = page.getRecords();
        //查询categoryName
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());
        List<ArticleVo> articleVos = BeanCopyUtils.copyBean(articles, ArticleVo.class);
        PageVo pageVo = new PageVo(articles,page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticledetails(Long id) {

        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        lambdaQueryWrapper.eq(Article::getId,id);
        Article article = articleService.getBaseMapper().selectOne(lambdaQueryWrapper);
        String name = categoryService.getById(article.getCategoryId()).getName();
        //获取redis中的viewcount值
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        //因为之前存入redis中的viewCount为了能够加减改成了integer类型，所以现在需要转换回来
        article.setViewCount(viewCount.longValue());
        article.setCategoryName(name);
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);

        return  ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {

        //更新redis中的数据
redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);



        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult addBlog(ArticleDto articleDto) {
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        boolean save = save(article);
        Long id = article.getId();
        List<Long> tags = articleDto.getTags();
        boolean saveTag=false;
        for ( Long tag:tags ) {
            SgArticleTag sgArticleTag = new SgArticleTag(id, tag);
            saveTag = sgArticleTagService.save(sgArticleTag);
        }

        if(save&&saveTag){
            return ResponseResult.okResult();
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.BLOG_INSERT_ERROR);
    }

    @Override
    public ResponseResult deleteArticleList(List<Long> idList) {
        idList.stream()
                .forEach(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) {
                        UpdateWrapper<Article> articleUpdateWrapper = new UpdateWrapper<Article>();
                        articleUpdateWrapper.eq("id",aLong).set("del_flag",1);
                        boolean update = articleService.update(articleUpdateWrapper);
                        if(!update){
                            throw new SystemException(AppHttpCodeEnum.DELETE_ERROR);
                        }


                    }
                });
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getArticleById(Long id) {

        Article article = articleService.getBaseMapper().selectById(id);
        //根据文章id查询出tagid
        LambdaQueryWrapper<SgArticleTag> tagQueryWrapper = new LambdaQueryWrapper<>();
        tagQueryWrapper.eq(SgArticleTag::getArticleId,id);
        List<SgArticleTag> sgArticleTags = sgArticleTagService.getBaseMapper().selectList(tagQueryWrapper);
        List<Long> tagList = sgArticleTags.stream()
                .map(sgArticleTag -> sgArticleTag.getTagId())
                .collect(Collectors.toList());
        //将数据查出并且封装成vo
        UpdateArticleBlogVO updateArticleBlogVO = BeanCopyUtils.copyBean(article, UpdateArticleBlogVO.class);
        updateArticleBlogVO.setTags(tagList);


        return ResponseResult.okResult(updateArticleBlogVO);
    }

    @Override
    public ResponseResult getArticleByTitle(Integer pageNum, Integer pageSize, String title, String summary) {
        Page<Article> articlePage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //模糊匹配，如果有title，那么就把title的查询条件加上
        articleLambdaQueryWrapper
                .like(StringUtils.hasText(title),Article::getTitle,title)
                 .like(StringUtils.hasText(summary),Article::getSummary,summary);

       // articleLambdaQueryWrapper.like();
        Page<Article> page = page(articlePage, articleLambdaQueryWrapper);
        List<Article> articleList= page.getRecords();
        long total = page.getTotal();
        PageVo pageVo = new PageVo(articleList, total);
        return ResponseResult.okResult(pageVo);
    }


}
